<script setup lang="ts">
import { ref, onMounted } from "vue"
import { useAuthStore } from "@/stores/auth"
import request from "@/utils/request"
import { ElMessage } from "element-plus"
import { User, VideoCamera, Present, CreditCard, DataAnalysis, Loading, Document } from "@element-plus/icons-vue"

const authStore = useAuthStore()
const loading = ref(true)

// 统计数据接口定义（与PC端保持一致）
interface DashboardStats {
  users: {
    total: number
    active: number
    partners: number
    todayNew: number
  }
  recharges: {
    total: number
    approved: number
    pending: number
    today: number
    totalAmount: number
    approvedAmount: number
  }
  withdrawals: {
    total: number
    approved: number
    pending: number
    totalAmount: number
    approvedAmount: number
  }
  gifts: {
    totalSends: number
    todaySends: number
    totalPoints: string
    todayPoints: string
    totalChatGifts: number
    todayChatGifts: number
    totalChatGiftPoints: string
    todayChatGiftPoints: string
  }
  content: {
    totalChannels: number
    activeChannels: number
    totalLiveRooms: number
    activeLiveRooms: number
    totalChatRooms: number
    activeChatRooms: number
  }
}
const stats = ref<DashboardStats | null>(null)

// 获取统计数据
async function fetchStats() {
  try {
    // 使用与PC端相同的API接口
    const response = await request.get("/api/admin/dashboard")
    stats.value = response.data
  } catch (error) {
    console.error("获取统计数据失败:", error)
    // 如果API失败，使用模拟数据
    stats.value = {
      users: {
        total: 1250,
        active: 89,
        partners: 15,
        todayNew: 8,
      },
      recharges: {
        total: 450,
        approved: 420,
        pending: 30,
        today: 25,
        totalAmount: 12500000,
        approvedAmount: 11800000,
      },
      withdrawals: {
        total: 180,
        approved: 165,
        pending: 15,
        totalAmount: 3200000,
        approvedAmount: 2950000,
      },
      gifts: {
        totalSends: 3420,
        todaySends: 156,
        totalPoints: "5680000",
        todayPoints: "125000",
        totalChatGifts: 8900,
        todayChatGifts: 340,
        totalChatGiftPoints: "2340000",
        todayChatGiftPoints: "45000",
      },
      content: {
        totalChannels: 45,
        activeChannels: 32,
        totalLiveRooms: 78,
        activeLiveRooms: 12,
        totalChatRooms: 156,
        activeChatRooms: 89,
      },
    }
  }
}

// 初始化数据
async function initData() {
  loading.value = true
  try {
    fetchStats()
  } catch (error) {
    ElMessage.error("데이터 로드 실패")
  } finally {
    loading.value = false
  }
}

// 格式化数字
function formatNumber(num: number) {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M"
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + "K"
  }
  return num.toString()
}

onMounted(() => {
  initData()
})
</script>

<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <div class="welcome-section mobile-padding">
      <div class="welcome-card mobile-card">
        <div class="welcome-content">
          <h2>안녕하세요, {{ authStore.user.name || "관리자" }}님!</h2>
          <p>{{ authStore.isAdmin ? "관리자" : "파트너" }} 대시보드에 오신 것을 환영합니다</p>
        </div>
        <el-icon size="48" color="#409EFF">
          <User />
        </el-icon>
      </div>
    </div>

    <!-- 사용자 통계 -->
    <div v-if="stats" class="stats-section mobile-padding">
      <div class="mobile-card">
        <div class="mobile-card-title">
          <el-icon>
            <User />
          </el-icon>
          사용자 통계
        </div>
        <div class="mobile-stats-grid">
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.users.total) }}</div>
            <div class="mobile-stats-label">총 등록 회원</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.users.active) }}</div>
            <div class="mobile-stats-label">활성 사용자</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.users.partners) }}</div>
            <div class="mobile-stats-label">파트너</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.users.todayNew) }}</div>
            <div class="mobile-stats-label">오늘 신규</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 충전 통계 -->
    <div v-if="stats" class="stats-section mobile-padding">
      <div class="mobile-card">
        <div class="mobile-card-title">
          <el-icon>
            <CreditCard />
          </el-icon>
          충전 통계
        </div>
        <div class="mobile-stats-grid">
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.recharges.total) }}</div>
            <div class="mobile-stats-label">충전 주문 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.recharges.approved) }}</div>
            <div class="mobile-stats-label">승인된 주문</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.recharges.pending) }}</div>
            <div class="mobile-stats-label">대기 중인 주문</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.recharges.today) }}</div>
            <div class="mobile-stats-label">오늘 충전 주문</div>
          </div>
        </div>
        <div class="revenue-stats" style="margin-top: 16px">
          <div class="revenue-item">
            <span class="revenue-label">충전 총 금액</span>
            <span class="revenue-value">¥{{ formatNumber(stats.recharges.totalAmount) }}</span>
          </div>
          <div class="revenue-item">
            <span class="revenue-label">승인된 금액</span>
            <span class="revenue-value">¥{{ formatNumber(stats.recharges.approvedAmount) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 출금 통계 -->
    <div v-if="stats" class="stats-section mobile-padding">
      <div class="mobile-card">
        <div class="mobile-card-title">
          <el-icon>
            <CreditCard />
          </el-icon>
          출금 통계
        </div>
        <div class="mobile-stats-grid">
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.withdrawals.total) }}</div>
            <div class="mobile-stats-label">출금 신청 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.withdrawals.approved) }}</div>
            <div class="mobile-stats-label">승인된 신청</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.withdrawals.pending) }}</div>
            <div class="mobile-stats-label">대기 중인 신청</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">¥{{ formatNumber(stats.withdrawals.totalAmount) }}</div>
            <div class="mobile-stats-label">출금 총 금액</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 선물 통계 -->
    <div v-if="stats" class="stats-section mobile-padding">
      <div class="mobile-card">
        <div class="mobile-card-title">
          <el-icon>
            <Present />
          </el-icon>
          선물 통계
        </div>
        <div class="mobile-stats-grid">
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.gifts.totalSends) }}</div>
            <div class="mobile-stats-label">라이브 선물 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.gifts.todaySends) }}</div>
            <div class="mobile-stats-label">오늘 라이브 선물</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.gifts.totalChatGifts) }}</div>
            <div class="mobile-stats-label">채팅 선물 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.gifts.todayChatGifts) }}</div>
            <div class="mobile-stats-label">오늘 채팅 선물</div>
          </div>
        </div>
        <div class="revenue-stats" style="margin-top: 16px">
          <div class="revenue-item">
            <span class="revenue-label">라이브 선물 총 포인트</span>
            <span class="revenue-value">{{ formatNumber(Number(stats.gifts.totalPoints)) }}</span>
          </div>
          <div class="revenue-item">
            <span class="revenue-label">채팅 선물 총 포인트</span>
            <span class="revenue-value">{{ formatNumber(Number(stats.gifts.totalChatGiftPoints)) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 콘텐츠 통계 -->
    <div v-if="stats" class="stats-section mobile-padding">
      <div class="mobile-card">
        <div class="mobile-card-title">
          <el-icon>
            <VideoCamera />
          </el-icon>
          콘텐츠 통계
        </div>
        <div class="mobile-stats-grid">
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.content.totalChannels) }}</div>
            <div class="mobile-stats-label">채널 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.content.activeChannels) }}</div>
            <div class="mobile-stats-label">활성 채널</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.content.totalLiveRooms) }}</div>
            <div class="mobile-stats-label">라이브 방 총수</div>
          </div>
          <div class="mobile-stats-card">
            <div class="mobile-stats-value">{{ formatNumber(stats.content.activeLiveRooms) }}</div>
            <div class="mobile-stats-label">활성 라이브 방</div>
          </div>
        </div>
        <div class="revenue-stats" style="margin-top: 16px">
          <div class="revenue-item">
            <span class="revenue-label">총 채팅방 수</span>
            <span class="revenue-value">{{ formatNumber(stats.content.totalChatRooms) }}</span>
          </div>
          <div class="revenue-item">
            <span class="revenue-label">활성 채팅방</span>
            <span class="revenue-value">{{ formatNumber(stats.content.activeChatRooms) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  min-height: 100%;
  background-color: var(--el-bg-color-page);
}

.welcome-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.welcome-content h2 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.welcome-content p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.stats-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.mobile-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 16px;
}

.revenue-stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.revenue-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.revenue-item:last-child {
  border-bottom: none;
}

.revenue-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.revenue-value {
  font-size: 16px;
  font-weight: 600;
}

.revenue-value.today {
  color: var(--el-color-success);
}

.revenue-value.total {
  color: var(--el-color-primary);
}


/* 迷你统计卡片样式 */
.mini-stats-card {
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  padding: 12px 8px;
  text-align: center;
}

.mini-stats-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.mini-stats-label {
  font-size: 11px;
  color: var(--el-text-color-regular);
  line-height: 1.2;
}

/* 响应式调整 */
@media (max-width: 360px) {
  .mobile-stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .mini-stats-card {
    padding: 8px 4px;
  }

  .mini-stats-value {
    font-size: 14px;
  }

  .mini-stats-label {
    font-size: 10px;
  }
}
</style>
